package com.getpebble.android.http;

import android.content.Context;
import android.net.Uri;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.util.LocaleUtil;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.Response;
import com.koushikdutta.ion.builder.Builders.Any.B;
import com.koushikdutta.ion.builder.Builders.Any.F;
import com.koushikdutta.ion.builder.Builders.Any.U;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class HttpRequestUtil {
    public static final String TAG = HttpRequestUtil.class.getSimpleName();

    public static Response<JsonObject> fetchBootConfig(Context context, String customUrl, int timeoutMs) throws IllegalArgumentException, ExecutionException, InterruptedException, TimeoutException {
        Thread.currentThread().setContextClassLoader(HttpRequestUtil.class.getClassLoader());
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }
        String bootUrl = customUrl != null ? customUrl : PebbleApplication.getBootConfig().getBootConfigUrl();
        Trace.debug(TAG, "fetchBootConfig: " + bootUrl);
        return (Response) ((B) ((B) Ion.with(context).load(bootUrl)).setTimeout(timeoutMs)).asJsonObject().withResponse().get((long) timeoutMs, TimeUnit.MILLISECONDS);
    }

    public static void fetchMeData(Context context, boolean useAuthenticationMeEndpoint, String accessToken, FutureCallback<Response<JsonObject>> callback, int timeoutMs) throws IllegalArgumentException {
        Thread.currentThread().setContextClassLoader(HttpRequestUtil.class.getClassLoader());
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else if (accessToken == null) {
            throw new IllegalArgumentException("'accessToken' cannot be null!");
        } else if (callback == null) {
            throw new IllegalArgumentException("'callback' cannot be null!");
        } else {
            String url;
            if (useAuthenticationMeEndpoint) {
                url = PebbleApplication.getBootConfig().getAuthenticationMeUrl();
            } else {
                url = PebbleApplication.getBootConfig().getUsersMeUrl();
            }
            if (url == null) {
                throw new IllegalStateException("'url' cannot be null!");
            }
            ((B) ((B) ((B) Ion.with(context).load(url)).addHeader("Authorization", "Bearer " + accessToken)).setTimeout(timeoutMs)).asJsonObject().withResponse().setCallback(callback);
        }
    }

    public static Response<JsonObject> getLockerApps(Context context, int timeoutMs) throws IllegalArgumentException, ExecutionException, InterruptedException, TimeoutException {
        Thread.currentThread().setContextClassLoader(HttpRequestUtil.class.getClassLoader());
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }
        return (Response) ((B) ((B) Ion.with(context).load(PebbleApplication.getBootConfig().getLockerUrl())).addHeader("Authorization", "Bearer " + PebbleApplication.getSessionManager().peekAuthToken())).asJsonObject().withResponse().get((long) timeoutMs, TimeUnit.MILLISECONDS);
    }

    public static Response<JsonObject> fetchLanguages(Context context, int timeoutMs) throws IllegalArgumentException, ExecutionException, InterruptedException, TimeoutException {
        Thread.currentThread().setContextClassLoader(HttpRequestUtil.class.getClassLoader());
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }
        String languagesUrl = PebbleApplication.getBootConfig().getLanguagesUrl();
        String urlWithQueryParameters = Uri.parse(languagesUrl).buildUpon().appendQueryParameter("isoLocal", LocaleUtil.getCurrentLocaleTag()).appendQueryParameter("mobileVersion", "2.4.1").appendQueryParameter("mobilePlatform", "android").build().toString();
        Trace.debug(TAG, "Fetching language packs from: " + urlWithQueryParameters);
        MobileAppBehavior.logLanguagePackRequest(languagesUrl, urlWithQueryParameters);
        return (Response) ((B) Ion.with(context).load(urlWithQueryParameters)).asJsonObject().withResponse().get((long) timeoutMs, TimeUnit.MILLISECONDS);
    }

    public static Response<JsonObject> addAppToLocker(Context context, String addLink, int timeoutMs) throws IllegalArgumentException, ExecutionException, InterruptedException, TimeoutException {
        Thread.currentThread().setContextClassLoader(HttpRequestUtil.class.getClassLoader());
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else if (addLink != null) {
            return (Response) ((U) ((B) ((B) Ion.with(context).load(addLink)).addHeader("Authorization", "Bearer " + PebbleApplication.getSessionManager().peekAuthToken())).setBodyParameter("dummy", "dummy")).asJsonObject().withResponse().get((long) timeoutMs, TimeUnit.MILLISECONDS);
        } else {
            throw new IllegalArgumentException("'addLink' cannot be null!");
        }
    }

    public static Response<JsonObject> deleteAppFromLocker(Context context, String deleteLink, int timeoutMs) throws IllegalArgumentException, ExecutionException, InterruptedException, TimeoutException {
        Thread.currentThread().setContextClassLoader(HttpRequestUtil.class.getClassLoader());
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else if (deleteLink != null) {
            return (Response) ((U) ((B) ((B) Ion.with(context).load(deleteLink)).addHeader("Authorization", "Bearer " + PebbleApplication.getSessionManager().peekAuthToken())).setBodyParameter("dummy", "dummy")).asJsonObject().withResponse().get((long) timeoutMs, TimeUnit.MILLISECONDS);
        } else {
            throw new IllegalArgumentException("'deleteLink' cannot be null!");
        }
    }

    public static void updateAppUuids(Context context, String updateUri, JsonObject query, final Runnable callback, int timeoutMs) {
        Thread.currentThread().setContextClassLoader(HttpRequestUtil.class.getClassLoader());
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else if (updateUri == null) {
            throw new IllegalArgumentException("'updateUri' cannot be null!");
        } else {
            Trace.debug(TAG, "Setting query to: " + query);
            ((F) ((B) ((B) ((B) Ion.with(context).load(updateUri)).setTimeout(timeoutMs)).addHeader("Authorization", "Bearer " + PebbleApplication.getSessionManager().peekAuthToken())).setJsonObjectBody(query)).asJsonObject().setCallback(new FutureCallback<JsonObject>() {
                public void onCompleted(Exception e, JsonObject jsonObject) {
                    if (e != null) {
                        Trace.error(HttpRequestUtil.TAG, "Failed to update app uuids: ", e);
                    } else {
                        Trace.debug(HttpRequestUtil.TAG, "Got json response: " + jsonObject);
                    }
                    callback.run();
                }
            });
        }
    }
}
